package cn.ljlao.mall.ware.ware.service.impl;

import cn.ljlao.common.constant.WareConstant;
import cn.ljlao.mall.ware.ware.entity.PurchaseDetailEntity;
import cn.ljlao.mall.ware.ware.service.PurchaseDetailService;
import cn.ljlao.mall.ware.ware.service.WareSkuService;
import cn.ljlao.mall.ware.ware.vo.DoneItemVo;
import cn.ljlao.mall.ware.ware.vo.DoneVo;
import cn.ljlao.mall.ware.ware.vo.MergeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ljlao.common.utils.PageUtils;
import cn.ljlao.common.utils.Query;

import cn.ljlao.mall.ware.ware.dao.PurchaseDao;
import cn.ljlao.mall.ware.ware.entity.PurchaseEntity;
import cn.ljlao.mall.ware.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    PurchaseService purchaseService;
    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(wa -> {
                wa.eq("id", key).or().like("assignee_name", key).or().like("phone", key);
            });
        }

        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList() {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(new HashMap<>()),
                new QueryWrapper<PurchaseEntity>().eq("status", "0").or().eq("status", "1")
        );

        return new PageUtils(page);

    }

    /**
     * 合并采购单
     * @param mergeVo
     */
    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // 如果采购id为null 说明没选采购单
        if (purchaseId == null) {
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());// 新建状态
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();// 自动返回id
        }
        PurchaseEntity byId = purchaseService.getById(purchaseId);
        //TODO 判断采购单状态
        if (byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
        ) {

            // 合并采购单 [其实就是修改上面创建的采购单]
            List<Long> items = mergeVo.getItems(); // 获取带过来的采购需求
            //查询所有的采购单
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailService.getBaseMapper().selectBatchIds(items);
            //过滤出 创建状态和已分配的 item id
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> entities = detailEntityList.stream()
                    .filter(item -> {
                        return item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                                item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode();
                    }).map(entity -> {
                        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                        purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                        purchaseDetailEntity.setId(entity.getId());
                        return purchaseDetailEntity;
                    }).collect(Collectors.toList());

            if (entities == null || entities.size() == 0) {
                return;
            }
            // 设置仓库id // 采购单得是同个仓库的
            //purchaseEntity.setWareId(detailEntities.get(0).getWareId());
            //修改采购单 对应的  '采购单id',
            purchaseDetailService.updateBatchById(entities);
            //修改 采购信息 表的 修改时间和 status
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);

        }
    }

    /**
     * 领取采购单
     * @param ids
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //获取所有符合要求的 采购单
        List<PurchaseEntity> collect = ids.stream()
                .map(id -> {
                    PurchaseEntity byId = this.getById(id);
                    return byId;
                })
                .filter(item -> {
                    Integer status = item.getStatus();
                    if (status == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                            status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());
        //修改所有采购单状态
        List<PurchaseEntity> purchaseEntities = collect.stream().map(item -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setId(item.getId());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());

        this.updateBatchById(purchaseEntities);

        //修改所有采购单详情状态
        for (PurchaseEntity item : collect) {
            List<PurchaseDetailEntity> list =  purchaseDetailService.getPurchaseDetaiByPurchaseId(item.getId());

            List<PurchaseDetailEntity> detailEntityList = list.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity pu = new PurchaseDetailEntity();
                pu.setId(purchaseDetailEntity.getId());
                pu.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return pu;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntityList);
        }

    }

    @Transactional
    @Override
    public void done(DoneVo doneVo) {
        //采购单id
        Long id = doneVo.getId();

        List<DoneItemVo> items = doneVo.getItems();
        boolean flag = true;
        List<PurchaseDetailEntity> list = new ArrayList<>();
        for (DoneItemVo item : items) {
            //修改订单状态 怎么着都要修改 放前面
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setStatus(item.getStatus());
            purchaseDetailEntity.setId(item.getItemId());
            list.add(purchaseDetailEntity);

            if (item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
            }else {
                //给完成的采购项 加库存
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStok(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
        }
        purchaseDetailService.updateBatchById(list);

        //修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }

}